package hku.cs.lunuo.cfg;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import soot.Body;
import soot.Scene;
import soot.SootClass;
import soot.SootMethod;
import soot.jimple.IfStmt;
import soot.options.Options;
import soot.toolkits.graph.Block;
import soot.toolkits.graph.ExceptionalBlockGraph;

public class CntPred {

	public static void main(String[] args) {
		Options.v().set_keep_line_number(true);
		Scene.v().loadBasicClasses();
		SootClass sc = Scene.v().loadClassAndSupport(args[0]);
		List<SootMethod> ms = sc.getMethods();
		
		HashMap<Integer, List<Integer>> hm = new HashMap<Integer, List<Integer>>();
		for(SootMethod sm : ms) {
			Body b = sm.retrieveActiveBody();
			ExceptionalBlockGraph bGraph = new ExceptionalBlockGraph(b);
			Iterator<Block> blockIt = bGraph.getBlocks().iterator();
			
			List<Block> blockLs= bGraph.getBlocks();
			for(int i=0; i<blockLs.size(); i++) {
				if(blockLs.get(i).getTail() instanceof IfStmt) {
					int j = i;
					List<Integer> li;
					if((li = hm.get(i))==null)
						li = new ArrayList<Integer>();
					li.add(i);
					while(j<blockLs.size() && blockLs.get(j+1).getHead() instanceof IfStmt) {
						j++;
						li.add(j);
					}
					hm.put(i, li);
					i = j;
				}
			}
			
//			while (blockIt.hasNext()) {
//				Block block = (Block) blockIt.next();
//				int blkIdx = block.getIndexInMethod();
//				
//				Unit u = block.getTail();
//				if(u instanceof IfStmt) {
//					int lineNum = Integer.parseInt(u.getTag("LineNumberTag").toString());
//					List<Integer> li;
//					if((li = hm.get(lineNum))==null)
//						li = new ArrayList<Integer>();
//					li.add(blkIdx);
//					hm.put(lineNum, li);
//				}
//			}
		}
		
		for(Integer i : hm.keySet()) {
			List<Integer> li = hm.get(i);
			System.out.print(i+":");
			for(Integer j : li) {
				System.out.print(j+ " ");
			}
			System.out.println();
		}
	}
}
